import 'package:flutter/material.dart';

import 'chat_input_bar.dart';
import 'chat_model.dart';
import 'chat_viewmodel.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> with WidgetsBindingObserver {
  final ScrollController _scrollController = ScrollController();
  final GlobalKey<ChatInputBarState> _chatInputBarKey = GlobalKey();
  final List _models = [];

  @override
  void initState() {
    super.initState();

    _models.addAll(ChatViewModel.models);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green,
      //键盘弹出页面不会上移 禁止页面上移
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text("聊天界面"),
      ),
      body: Container(
        color: Colors.green,
        width: double.infinity,
        height: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _buildListView(),
            _buildInputBar(),
          ],
        ),
      ),
    );
  }

  _buildListView() {
    return Flexible(
        child: GestureDetector(
      onPanDown: (_) {
        _chatInputBarKey.currentState!.hidenKeyBoard();
      },
      child: ListView.builder(
          padding: EdgeInsets.zero,
          //让内容反转，滚动到最下面
          reverse: true,
          shrinkWrap: true,
          controller: _scrollController,
          itemCount: _models.length,
          itemBuilder: (ctx, index) {
            if (_models[index].name == "刘亦菲") {
              return _buildLeftContent(_models[index]);
            }
            return _builRightContent(_models[index]);
          }),
    ));
  }

  _buildLeftContent(ChatModel model) {
    return Container(
      padding: const EdgeInsets.all(15),
      alignment: Alignment.center,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.asset(
                "lib/images/default_head.png",
                width: 35,
                height: 35,
              ),
              Flexible(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(
                      left: 10,
                    ),
                    child: Text(model.name!,
                        style: const TextStyle(color: Colors.white)),
                  ),
                  Container(
                    constraints: const BoxConstraints(
                      maxWidth: 300,
                    ),
                    margin: const EdgeInsets.only(top: 10, left: 10),
                    padding: const EdgeInsets.fromLTRB(13, 6, 13, 8),
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(18),
                        bottomLeft: Radius.circular(18),
                        bottomRight: Radius.circular(18),
                      ),
                    ),
                    child: GestureDetector(
                      onTap: () {
                        print('点击');
                      },
                      onLongPress: () {
                        print("长按");
                      },
                      child: ChatViewModel.getRichText(model.chatStr!),
                    ),
                  )
                ],
              ))
            ],
          ),
        ],
      ),
    );
  }

  _builRightContent(ChatModel model) {
    return Container(
      padding: const EdgeInsets.all(15),
      alignment: Alignment.center,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(
                      right: 15,
                    ),
                    child: Text(model.name!,
                        style: const TextStyle(color: Colors.white)),
                  ),
                  Container(
                    constraints: const BoxConstraints(
                      maxWidth: 300,
                    ),
                    margin: const EdgeInsets.only(top: 10, right: 10),
                    padding: const EdgeInsets.fromLTRB(13, 6, 13, 8),
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(18),
                        bottomLeft: Radius.circular(18),
                        bottomRight: Radius.circular(18),
                      ),
                    ),
                    child: GestureDetector(
                      onTap: () {
                        print('点击');
                      },
                      onLongPress: () {
                        print("长按");
                      },
                      child: ChatViewModel.getRichText(model.chatStr!),
                    ),
                  )
                ],
              ),
              Flexible(
                child: Image.asset(
                  "lib/images/default_head.png",
                  width: 35,
                  height: 35,
                ),
              )
            ],
          ),
        ],
      ),
    );
  }

  _buildInputBar() {
    return ChatInputBar(
        key: _chatInputBarKey,
        textHandle: (String text) {
          ChatModel model = ChatModel(
            name: "小四",
            chatStr: text,
          );
          setState(() {
            _models.insert(0, model);
          });

          _scrollController.animateTo(0.0,
              duration: const Duration(milliseconds: 200),
              curve: Curves.linear);
        });
  }
}
